package com.ibiaoke.boss.controller;

import com.ibiaoke.common.base.BaseController;
import com.ibiaoke.common.base.Page;
import com.ibiaoke.common.consts.WeChatConsts;
import com.ibiaoke.common.response.Res;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.common.utils.DesUtils;
import com.ibiaoke.common.utils.IPUtil;
import com.ibiaoke.customer.consts.PayTypeConst;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.marketing.consts.CouponReceiveConsts;
import com.ibiaoke.marketing.entity.CouponReceive;
import com.ibiaoke.marketing.service.CouponReceiveService;
import com.ibiaoke.order.consts.OrderStatusConst;
import com.ibiaoke.order.entity.Order;
import com.ibiaoke.order.entity.XcxOrder;
import com.ibiaoke.order.entity.so.OrderSO;
import com.ibiaoke.order.entity.so.SubmitOrderSO;
import com.ibiaoke.order.entity.vo.OrderVO;
import com.ibiaoke.order.service.OrderPayService;
import com.ibiaoke.order.service.OrderService;

import com.ibiaoke.order.service.XcxOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by biaoke on 2017/6/23.
 */
@Controller
public class WxOrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CouponReceiveService couponReceiveService;

    @Autowired
    private OrderPayService orderPayService;

    @Autowired
    private XcxOrderService xcxOrderService;

    /**
     * 查询个人所有订单
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("/listOrder")
    public Res listOrder(OrderSO orderSO, Page page) {
        Customer customer = getLoginUser();
        orderSO.setUserId(customer.getCustomerId());
        List<OrderVO> list = orderService.listOpenOrder(orderSO, page);
        return Res.create().addResponse("page", page).addResponse("orderList", list);
    }

    /**
     * 购物车下单
     *
     * @param submitOrderSO
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping("/submitShoppingCartOrder")
    public Res submitShoppingCartOrder(@Valid SubmitOrderSO submitOrderSO, BindingResult result) {
        if(!"1".equals(submitOrderSO.getDeliveryType())){
            handleValidate(result);
        }
        Customer customer = getLoginUser();
        submitOrderSO.setUserId(customer.getCustomerId());
        Integer orderId = orderService.submitShoppingCartOrder(submitOrderSO);
        return Res.create().addResponse("orderId", orderId);
    }

    /**
     * 商品直接下单
     *
     * @param submitOrderSO
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping("/submitGoodsOrder")
    public Res submitGoodsOrder(@Valid SubmitOrderSO submitOrderSO, BindingResult result) {
        if(!"1".equals(submitOrderSO.getDeliveryType())){
            handleValidate(result);
        }
        Customer customer = getLoginUser();
        submitOrderSO.setUserId(customer.getCustomerId());
        Integer orderId = orderService.submitGoodsOrder(submitOrderSO);
        return Res.create().addResponse("orderId", orderId);
    }

    /**
     * 订单数量查询
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOrderNum")
    public Res getOrderNum() {
        Customer customer = getLoginUser();
        //待付款
        Long unpaidCount = orderService.getOrderNum(customer.getCustomerId(), OrderStatusConst.UNPAID);
        //待收货
        Long paidCount = orderService.getOrderNum(customer.getCustomerId(), OrderStatusConst.PAID);
        paidCount = paidCount + orderService.getOrderNum(customer.getCustomerId(), OrderStatusConst.DELIVERED);
        //已完成
        Long receivedCount = orderService.getOrderNum(customer.getCustomerId(), OrderStatusConst.RECEIVED);

        return Res.create().addResponse("unpaidCount", unpaidCount).addResponse("paidCount", paidCount).addResponse("receivedCount", receivedCount);
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping("/cancelOrder")
    public Res cancelOrder(Integer orderId) {
        Customer customer = getLoginUser();
        orderService.cancelOrder(customer.getCustomerId(), orderId);
        return Res.create();
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping("/confirmOrder")
    public Res confirmOrder(Integer orderId) {
        Customer customer = getLoginUser();
        orderService.confirmOrder(customer.getCustomerId(), orderId);
        return Res.create();
    }


    /**
     * 获取订单详情
     *
     * @param code
     * @return
     */
    @RequestMapping("/getOrderWithCode")
    @ResponseBody
    public Res getOrderWithCode(String code) {
        Integer orderId = Integer.valueOf(DesUtils.decrypt(code));
        OrderVO orderVO = orderService.getOrder(orderId);
        return Res.create().addResponse("order", orderVO);
    }

    /**
     * 获取订单详情
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/getOrder")
    @ResponseBody
    public Res getOrder(Integer orderId) {
        Customer customer = getLoginUser();
        OrderVO orderVO = orderService.getOrder(orderId);
        return Res.create().addResponse("order", orderVO);
    }


    /**
     * 查询订单和优惠券数量
     */
    @RequestMapping("/getOrdersAndCouponCount")
    @ResponseBody
    public Res getOrdersAndCouponCount() {
        Res res = getOrderNum();
        Customer customer = getLoginUser();
        AssertUtils.notNull(customer, "请登录");
        Long couponCount = couponReceiveService.countUnusedCouponReceive(customer.getCustomerId());
        return res.addResponse("availableCouponNum", couponCount);
    }

    /**
     * 订单支付
     * @param orderId
     * @param payType
     * @param smsCode
     * @return
     */
    @RequestMapping("/payOrder")
    @ResponseBody
    public Res payOrder(Integer orderId, Integer payType, String smsCode, HttpServletRequest request) {
        String openId = (String) getSession().getAttribute(WeChatConsts.OPEN_ID);
        //微商城——微信支付
        if (payType == PayTypeConst.WECAHT) {
            Map<String, String> payInfo = orderPayService.payOrderByWeChat(orderId, openId);
            return Res.create().addResponse("payInfo", payInfo);
        }
        //微商城——支付宝支付
        if (payType == PayTypeConst.ALIPAY) {
            String form = orderPayService.payOrderByAliPay(orderId);
            return Res.create().addResponse("form", form);
        }
         //App微信支付
        if (payType == PayTypeConst.APP_WECAHT) {
            String ip = IPUtil.getIp(request);
            Map<String, Object> payInfo = orderPayService.payOrderByAppWeChat(orderId,ip);
            return Res.create().addResponse("payInfo", payInfo);
        }
        //App支付宝支付
        if (payType == PayTypeConst.APP_ALIPAY) {
            String orderStr = orderPayService.payOrderByAppAliPay(orderId);
            return Res.create().addResponse("orderStr", orderStr);
        }
        //预存款支付
        if (payType == PayTypeConst.DEPOSIT) {
            Customer customer = getLoginUser();
            orderPayService.payOrderByDepositPay(orderId, customer, smsCode);
            return Res.create();
        }
        return Res.create();
    }

    @RequestMapping("/listShopOrder")
    @ResponseBody
    public Res listShopOrder(Integer shopId) {
        List<Order> orderList = orderService.listShopOrder(shopId);
        return new Res().addResponse("orderList",orderList);
    }


    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }
    /**
     * 购物车下单
     *
     * @param submitOrderSO
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping("/newSubmitShoppingCartOrder")
    public Res newSubmitShoppingCartOrder(@Valid SubmitOrderSO submitOrderSO, BindingResult result) {
        Customer customer = getLoginUser();
        if(!"1".equals(submitOrderSO.getDeliveryType())){
            handleValidate(result);
        }
        submitOrderSO.setUserId(customer.getCustomerId());
        List<XcxOrder> list = xcxOrderService.submitShoppingCartOrder(submitOrderSO);
        List<Integer> orderIds = list.stream().map(XcxOrder::getOrderId).collect(Collectors.toList());
        return Res.create().addResponse("orderIds", orderIds);
    }
}
